<?php
namespace app\admin\controller;

use app\common\AdminController;
use app\common\exception\AdminException;
use app\admin\model\Appin as AM;
use app\admin\validate\AppinValidate as AV;

class Appin extends AdminController
{
    protected $validate = AV::class;

    /**
     * [shop 应用商店]
     * @return [type] [description]
     */
    public function shop()
    {
        return view();
    }

    /**
     * [installed 已安装应用]
     * @return [type] [description]
     */
    public function installed()
    {
        return view('',[
            'appins' => AM::select()
        ]);
    }

    /**
     * [localapp 获取本地所有的应用列表]
     * @return [type] [description]
     */
    public function localapp()
    {
        return view('', [
            'appins' => list_local_app()
        ]);
    }

    /**
     * [install 安装脚本]
     * @return [type] [description]
     */
   public function install()
   {
       $tag_name = $this->request->param('tag', '', 'strip_tags');
	   $action = $this->request->param('act', '', 'strip_tags');
	   
	   #重新加载配置
	   if ($action === 'reset') {
		   $reload = \app\appin\service\Package::install($tag_name);
		   return $this->successRender();
	   }
	   
       $app_path = $this->app->appin_path . '/' . $tag_name . '/app.php';
       if ( !file_exists($app_path) ) {
           throw new AdminException('应用配置文件不存在');
       }
       $app = include $app_path;
       $installRes = AM::create([
           'name'       => $app['name'],
           'tag_name'   => $app['tag_name'],
           'author'     => $app['author'],
           'version'    => $app['version'],
           'worker_id'  => session('admin.worker.id')
       ]);

       install_app($tag_name);
       return $this->successRender(['url' => $app['install_uri']]);
   }
}
